package com.ruoyi.mall.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.TreeBuildUtils;
import com.ruoyi.mall.domain.MallGoodsSpecifications;
import com.ruoyi.mall.domain.bo.GoodsSpecificationsBo;
import com.ruoyi.mall.domain.bo.MallGoodsCategoryBo;
import com.ruoyi.mall.domain.bo.MallGoodsSpecificationsBo;
import com.ruoyi.mall.domain.vo.GoodsSpecificationsVo;
import com.ruoyi.mall.domain.vo.MallGoodsCategoryVo;
import com.ruoyi.mall.domain.vo.MallGoodsSpecificationsVo;
import com.ruoyi.mall.service.IGoodsSpecificationsService;
import com.ruoyi.mall.service.IMallGoodsCategoryService;
import com.ruoyi.mall.service.IMallGoodsSpecificationsService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.domain.bo.MallGoodsBo;
import com.ruoyi.mall.domain.vo.MallGoodsVo;
import com.ruoyi.mall.domain.MallGoods;
import com.ruoyi.mall.mapper.MallGoodsMapper;
import com.ruoyi.mall.service.IMallGoodsService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 商城商品信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-24
 */
@RequiredArgsConstructor
@Service
public class MallGoodsServiceImpl implements IMallGoodsService {

    private final MallGoodsMapper baseMapper;
    @Autowired
    private IGoodsSpecificationsService goodsSpecificationsService;
    @Autowired
    private IMallGoodsSpecificationsService mallGoodsSpecificationsService;
    @Autowired
    private IMallGoodsCategoryService mallGoodsCategoryService;

    /**
     * 查询商城商品信息
     */
    @Override
    public MallGoodsVo queryById(Long goodsId){
        GoodsSpecificationsBo goodsSpecificationsBo = new GoodsSpecificationsBo();
        List<GoodsSpecificationsVo> lstGoodsSpecificationsVo = goodsSpecificationsService.queryList(goodsSpecificationsBo);
        MallGoodsSpecificationsBo mallGoodsSpecificationsBo = new MallGoodsSpecificationsBo();
        mallGoodsSpecificationsBo.setGoodsId(goodsId);
        List<MallGoodsSpecificationsVo> lstMallGoodsSpecificationsVoList = mallGoodsSpecificationsService.queryList(mallGoodsSpecificationsBo);
        MallGoodsVo mallGoodsVo = baseMapper.selectVoById(goodsId);
        if (mallGoodsVo.getLstGoodsSpecifications()==null)
        {
            mallGoodsVo.setLstGoodsSpecifications(new ArrayList<>());
        }
        for (MallGoodsSpecificationsVo mallGoodsSpecificationsVo :lstMallGoodsSpecificationsVoList)
        {
            GoodsSpecificationsVo goodsSpecificationsVo = lstGoodsSpecificationsVo.stream().filter(item -> item.getGoodsSpecificationsId().equals(mallGoodsSpecificationsVo.getGoodsSpecificationsId())).findFirst().orElse(null);
            if (goodsSpecificationsVo != null)
            {
                mallGoodsVo.getLstGoodsSpecifications().add(goodsSpecificationsVo);
            }
        }
        return mallGoodsVo;
    }

    /**
     * 查询商城商品信息列表
     */
    @Override
    public TableDataInfo<MallGoodsVo> queryPageList(MallGoodsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MallGoods> lqw = buildQueryWrapper(bo);
        Page<MallGoodsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询商城商品信息列表
     */
    @Override
    public List<MallGoodsVo> queryList(MallGoodsBo bo) {
        LambdaQueryWrapper<MallGoods> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<Tree<Long>> selectCategoryTreeList(MallGoodsCategoryVo goodsCategoryBo)
    {
        MallGoodsCategoryBo query = new MallGoodsCategoryBo();
        mallGoodsCategoryService.queryList(query);
        List<MallGoodsCategoryVo> lstMallGoodsCategory = mallGoodsCategoryService.queryList(query);
        return buildCategoryTreeSelect(lstMallGoodsCategory);
    }
    /**
     * 构建前端所需要下拉树结构
     *
     * @param goodsCategoryVoList 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<Tree<Long>> buildCategoryTreeSelect(List<MallGoodsCategoryVo> goodsCategoryVoList) {
        if (CollUtil.isEmpty(goodsCategoryVoList)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(goodsCategoryVoList, (categoryBo, tree) ->
            tree.setId(categoryBo.getCategoryId())
                .setParentId(categoryBo.getParentId())
                .setName(categoryBo.getCategoryName())
                .setWeight(0));
    }

    private LambdaQueryWrapper<MallGoods> buildQueryWrapper(MallGoodsBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallGoods> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCategoryId() != null, MallGoods::getCategoryId, bo.getCategoryId());
        lqw.like(StringUtils.isNotBlank(bo.getGoodsName()), MallGoods::getGoodsName, bo.getGoodsName());
        lqw.like(StringUtils.isNotBlank(bo.getGoodsShortName()), MallGoods::getGoodsShortName, bo.getGoodsShortName());
        lqw.eq(bo.getGoodsImg()!=null, MallGoods::getGoodsImg, bo.getGoodsImg());
        lqw.eq(bo.getGoodsSmallImg()!=null, MallGoods::getGoodsSmallImg, bo.getGoodsSmallImg());
        lqw.eq(bo.getGoodsBigImg()!=null, MallGoods::getGoodsBigImg, bo.getGoodsBigImg());
        lqw.eq(StringUtils.isNotBlank(bo.getGoodsDesc()), MallGoods::getGoodsDesc, bo.getGoodsDesc());
        lqw.eq(StringUtils.isNotBlank(bo.getGoodsInstructions()), MallGoods::getGoodsInstructions, bo.getGoodsInstructions());
        lqw.eq(bo.getPayRule() != null, MallGoods::getPayRule, bo.getPayRule());
        lqw.eq(bo.getGoodsScore() != null, MallGoods::getGoodsScore, bo.getGoodsScore());
        lqw.eq(bo.getGoodsMoney() != null, MallGoods::getGoodsMoney, bo.getGoodsMoney());
        lqw.eq(bo.getGoodsStatus() != null, MallGoods::getGoodsStatus, bo.getGoodsStatus());
        lqw.eq(bo.getYn() != null, MallGoods::getYn, bo.getYn());
        return lqw;
    }

    /**
     * 新增商城商品信息
     */
    @Override
    public Boolean insertByBo(MallGoodsBo bo) {
        MallGoods add = BeanUtil.toBean(bo, MallGoods.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag)
        {
            bo.setGoodsId(add.getGoodsId());
            if (bo.getLstGoodsSpecifications() != null)
            {
                fillGoodsSpecifications(bo);
            }
        }
        return flag;
    }

    /**
     * 修改商城商品信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean updateByBo(MallGoodsBo bo)
    {
        MallGoods update = BeanUtil.toBean(bo, MallGoods.class);
        validEntityBeforeSave(update);
        MallGoodsSpecificationsBo query = new MallGoodsSpecificationsBo();
        query.setGoodsId(bo.getGoodsId());
        List<MallGoodsSpecificationsVo> lstMallGoodsSpecifications = mallGoodsSpecificationsService.queryList(query);
        Collection<Long> ids = new ArrayList<>();
        for (MallGoodsSpecificationsVo mallGoodsSpecificationsVo : lstMallGoodsSpecifications)
        {
            ids.add(mallGoodsSpecificationsVo.getMallGoodsSpecificationsId());
        }
        boolean result = baseMapper.updateById(update) > 0;
        if (result)
        {
            if (ids.size() > 0)
            {
                mallGoodsSpecificationsService.deleteWithValidByIds(ids, false);
            }
            fillGoodsSpecifications(bo);
        }
        return result;
    }

    /**
     * 填充商品规格信息列表
     * @param
     */
    public void fillGoodsSpecifications(MallGoodsBo bo)
    {
        for (GoodsSpecificationsVo goodsSpecifications :bo.getLstGoodsSpecifications())
        {
            MallGoodsSpecificationsBo mallGoodsSpecifications = new MallGoodsSpecificationsBo();
            mallGoodsSpecifications.setGoodsId(bo.getGoodsId());
            mallGoodsSpecifications.setGoodsSpecificationsId(goodsSpecifications.getGoodsSpecificationsId());
            mallGoodsSpecificationsService.insertByBo(mallGoodsSpecifications);
        }
    }


    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallGoods entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商城商品信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
